use std::cell::RefCell;
use std::rc::Rc;
use chrono::Local;
use yew::Callback;
use yewdux::Dispatch;
use crate::business::page::fragment::im_session_list_view::{SessionAction, SessionListState};
use crate::business::service::message_receive_service::MessageReceiveService;
use crate::business::service::save_message_service::SaveMessageService;
use crate::business::websocket::dto::common_dto::{ExceptionResp, OkResp};
use crate::business::websocket::dto::im_message_dto::{MessageObject, MessageReadReq};
use crate::business::websocket::receive_send_handle::{ImReceiveSendActionMessage};

// 接受消息
pub fn receive_message(session_list_dispatch: Dispatch<SessionListState>, show_message_callback: Rc<RefCell<Callback<ImReceiveSendActionMessage>>>, login_user_id: String, message_object: MessageObject) -> Result<OkResp, ExceptionResp> {
    log::info!("receive message, info: {:?}", message_object);

    let messages = SaveMessageService::save_messages(login_user_id, vec![message_object], false);
    if !messages.is_empty() {
        for message in messages.iter() {
            if let Some(session) = message.session.clone() {
                log::info!("receive update session33: {:?}", session);
                session_list_dispatch.apply(SessionAction::UpdateSession(session));
            }
        }
        let show_message_callback = show_message_callback.clone().borrow().clone();
        show_message_callback.emit(ImReceiveSendActionMessage::Show(messages));
    }

    Ok(OkResp {
        success_data_time: Local::now(),
        local_seq: Some("".to_string()),
        coder: 0,
        other_info: None,
    })
}

pub fn receive_read_message(action_message_callback: Rc<RefCell<Callback<ImReceiveSendActionMessage>>>, login_user_id: String, message_read_req: MessageReadReq) -> Result<OkResp, ExceptionResp> {
    log::info!("receive read message, info: {:?}", message_read_req);
    let update_messages = MessageReceiveService::receive_read_message(&login_user_id, message_read_req.message_ids);

    let update_message_callback = action_message_callback.clone().borrow().clone();
    update_message_callback.emit(ImReceiveSendActionMessage::Update(update_messages));

    Ok(OkResp {
        success_data_time: Local::now(),
        local_seq: Some("".to_string()),
        coder: 0,
        other_info: None,
    })
}